//
//  TestResultViewController.m
//  MIDI
//
//  Created by E.M.Game on 15/10/8.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "TestResultViewController.h"
#import "TestResultCell.h"
#import "AppConfig.h"
#import "UIViewController+NavItem.h"
#import "APIAdress.h"
#import "MBProgressHUD+YC.h"
#import "QXNetWorkTool.h"
#import "TestDetailModel.h"
#import "EvaluationTeacherViewController.h"
#import "UIViewController+Create.h"
#import "UIViewController+NavItem.h"
#import "SIAlertView.h"
#import "CertificatePayTipViewControl.h"
#import "ReciveCertificateModel.h"
#import "ViewTestOrderController.h"
#import "AccountTool.h"
#import "AliPayTool.h"
#import "WXPrePayIdModel.h"
#import "WeChatPayTool.h"
#import "UserDataSingleton.h"
#import "WXApi.h"
#import "PaySignCostAndCerficationCostModel.h"
#import "GetCerficationCostModel.h"
#import "TestResultCell.h"
#import "CommFunc.h"

@interface TestResultViewController ()<UITableViewDelegate , UITableViewDataSource,
                                        QXNetWorkToolDelegate,CertificatePayTipViewDeletage>

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (nonatomic , strong) TestDetailModel *model;
@property (nonatomic , strong) GetCerficationCostModel *getCerficationCostModel;

@property(strong , nonatomic) PaySignCostAndCerficationCostModel * orderData; //订单数据
@property(assign , nonatomic) int payType;

@property (nonatomic , strong) TestResultCell* myCell;

@end

@implementation TestResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self config];
    
    self.payType = -1;
    
    self.myTableView.showsVerticalScrollIndicator = NO;
}

- (void)config
{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;
    
    [tool GetDataFromServerWithPostMethodandInterfaceName:ExamDetailInterface andParameter:@[@{@"exam_id":self.exam_id}] tag:1];
    
    
    //获取工本费
//    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    QXNetWorkTool *tool2 = [[QXNetWorkTool alloc]init];
    
    tool2.QXNetWorkDelegate = self;
    
    [tool2 GetDataFromServerWithPostMethodandInterfaceName:GetCerficationCostInterface andParameter:@[@{@"param":@"no"}] tag:10];
}

- (void)GetFailResponse:(id)Response andTag:(int)tag
{
    switch (tag)
    {
        case 10:
        {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:(NSString *)Response toView:self.view];
            
            break;
        }
        case 8888:
            [MBProgressHUD hideHUDForView:self.view];
            //            [MBProgressHUD showSuccess:(NSString*)message];
            break;
        default:
        {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:(NSString *)Response toView:self.view];
            break;
        }
    }
}

- (void)GetSuccessMessage:(id)message andTag:(int)tag
{
    NSString *mes = message;
    
    [MBProgressHUD showSuccess:mes toView:self.view];
    
    switch (tag)
    {
        case 10:
        {
            [MBProgressHUD showSuccess:message toView:self.view];
            break;
        }
            
        case 8888:
        {
            //支付成功后，返回我的考试
            [MBProgressHUD hideHUD];
            
            if ([[AccountTool takePayResult] isEqualToString:VPaySuccess] )
            {
                if (self.myCell)
                {
                    [self setShowreciveCertificateBtn];
                }
            }
            
            break;
        }
    }
}

-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];

    switch (tag)
    {
        case 1:
        {
            for (NSDictionary *dic in Response)
            {
                self.model = [TestDetailModel TestDetailWithDict:dic];

                break;
            }
            [self.myTableView reloadData];
            break;
        }
            
            //TODO:wanglei
//        case 2://支付完成
//        {
//            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//            
//            TestResultCell *cell = (TestResultCell *)[self.myTableView cellForRowAtIndexPath:indexPath];
//            
//            if (cell)
//            {
//                cell.judgeTeacherBigBtn.hidden = YES;
//                cell.judgeTeacherLittleBtn.hidden = NO;
//                cell.payBtn.hidden = YES;
//                cell.reciveCertificateBtn.hidden = NO;
//            }
//            
//            break;
//        }
            
        case 2:
        {
            //生成订单
            for(NSDictionary * dic in Response)
            {
                PaySignCostAndCerficationCostModel * item = [PaySignCostAndCerficationCostModel PaySignCostAndCerficationCostWithDict:dic];
                self.orderData = item;
                
                [AccountTool saveOrderId:item.order_num];
                
                break;
            }
            
            if (self.payType == 0)
            {
                QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
                netTools.QXNetWorkDelegate = self;
                
                //微信支付
                int wxPrice = [self.getCerficationCostModel.price floatValue] * 100;
                NSString *strPrice = [[NSString alloc] initWithFormat:@"%d", wxPrice];
                
                //获得prepayid和noncestr
                [netTools GetDataFromServerWithPostMethodandInterfaceName:WXPayGetPrepayIdInterface andParameter:
                 @[@{
                       @"totalfee":strPrice,
                       @"body":@"证书工本费",
                       @"outtradeno":self.orderData.order_num
                       }] tag:3];
            }
            else if (self.payType == 1)
            {
                //支付宝支付
                [AccountTool saveOrderPrice:self.getCerficationCostModel.price];
                [AccountTool saveExamId:self.model.id];
                [AccountTool savePayItem:VPayCerficationCost];
                
                [AliPayTool alipayWithOrdercode:@"" orderId:self.orderData.order_num Price:self.getCerficationCostModel.price CityId:@"" Target:self];
            }
            
            self.payType = -1;
            
            break;
        }
        case 3:
        {
            for(NSDictionary * dic in Response)
            {
                WXPrePayIdModel * item = [WXPrePayIdModel WXPrePayIdModelWithDict:dic];
                
                NSString *prepayid = item.prepayid;
                NSString *noncestr = item.noncestr;
                
                int wxPrice = [self.getCerficationCostModel.price floatValue] * 100;
                NSString *strPrice = [[NSString alloc] initWithFormat:@"%d", wxPrice];
                
                //微信支付
                [AccountTool saveOrderPrice:strPrice];
                [AccountTool saveExamId:self.model.id];
                [AccountTool savePayItem:VPayCerficationCost];
                
                [WeChatPayTool WeChatWithOrdercode:@""
                                          prepayid:prepayid
                                           orderId:self.orderData.order_num
                                            Price :strPrice
                                            CityId:@""
                                          noncestr:noncestr
                                            Target:self];
                break;
            }
            break;
        }

        case 9: //收取证书
        {
            NSMutableArray* tmpData = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in Response)
            {
                ReciveCertificateModel *model = [ReciveCertificateModel ReciveCertificateWithDict:dic];
                
                [tmpData addObject:model];
            }
            
            ViewTestOrderController *obj = [ViewTestOrderController create];
            obj.data = tmpData;
            [self.navigationController pushViewController:obj animated:YES];
            
            break;
        }
        case 10:
        {
            for (NSDictionary *dic in Response)
            {
                self.getCerficationCostModel = [GetCerficationCostModel    GetCerficationCostWithDict:dic];
                
                break;
            }
            [self.myTableView reloadData];
            break;
        }
    }
}

//支付tip
-(void)payBtn:(UIButton *)sender
{
    if(self.getCerficationCostModel)
    {
        CertificatePayTipViewControl *obj = [CertificatePayTipViewControl create];
        obj.view.backgroundColor = [UIColor clearColor];
        obj.bgImage.alpha = 1;
        UIView *subView = [obj.view viewWithTag:999];
        subView.backgroundColor = [UIColor clearColor];
        
        obj.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        obj.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        obj.definesPresentationContext = YES;
        obj.deletage = self;
        
        [obj setTitleData:self.getCerficationCostModel.price];
        [self presentViewController:obj animated:YES completion:nil];
    }
}

//支付证书工本费
-(void)pay:(int)type
{
    if (type == 1) //微信
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"确认支付" message:nil
                                                            delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
        
        alertView.tag = 111;
        
        [alertView show];
    }
    else if (type == 2) //支付宝
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"确认支付" message:nil
                                                            delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
        
        alertView.tag = 222;
        
        [alertView show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 111)
    {
        //微信支付
        if (buttonIndex == 1)
        {
            self.payType = 0;
            [self WXPay];
            return;
        }
    }
    else if (alertView.tag == 222)
    {
        //支付宝支付
        if (buttonIndex == 1)
        {
            self.payType = 1;
            [self Alipay];
            return;
        }
    }
    else if (alertView.tag == 333)
    {
        //没有装微信
        return;
    }
}

-(void) WXPay
{
    if(![WXApi isWXAppInstalled]) // 判断 用户是否安装微信
    {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"您未安装微信，请安装后付款。"
                                  message:nil
                                  delegate:self
                                  cancelButtonTitle:@"确定"
                                  otherButtonTitles:nil, nil];
        
        alertView.tag = 333;
        [alertView show];
        return;
    }
    
    [self createOrder];
}

-(void) Alipay
{
    [self createOrder];
}

-(void) createOrder
{
    //生成订单
    UserDataSingleton *userData = [UserDataSingleton shareInstance];
    if(![userData isLogin])
    {
        [userData pleaseLogin:self];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *netTools = [[QXNetWorkTool alloc]init];
    netTools.QXNetWorkDelegate = self;
    
    //工本费
    [netTools GetDataFromServerWithPostMethodandInterfaceName:PaySignCostAndCerficationCostInterface andParameter:
        @[@{@"exam_id":self.model.id,
            @"type":@"2"}] tag:2];
}

//收取证书
-(void)reciveCertificate:(UIButton *)sender
{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    QXNetWorkTool *tool = [[QXNetWorkTool alloc]init];
    
    tool.QXNetWorkDelegate = self;
    
    [tool GetDataFromServerWithPostMethodandInterfaceName:ReciveCertificateInterface andParameter:@[@{@"exam_id":self.exam_id}] tag:9];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configNavigationItem];
}



-(void) configNavigationItem
{
    [self.navigationController.navigationBar setBarTintColor:MIDIColorOfNavigationBar];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.title = @"考试完成";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],UITextAttributeFont,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

#pragma mark tableView datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.myCell)
    {
        return [self.myCell getHeight];
    }
    
    return 469;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.myCell = nil;
    NSString *identifier = @"TestResultCell";
    self.myCell = [self.myTableView dequeueReusableCellWithIdentifier:identifier];
    if(self.myCell == nil)
    {
        self.myCell = [TestResultCell loadFromXib];
    }
    if (self.model && self.myCell)
    {
        self.myCell.contentView.hidden = NO;
        [self configCell:indexPath.row cell:self.myCell];
    }
    return self.myCell;
}

#pragma mark - Table View Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)configCell :(NSInteger)row cell:(TestResultCell *) mycell
{
    mycell.socreLb.text = self.model.grade_score;
    mycell.socreLb.text = [mycell.socreLb.text stringByAppendingString:@"分"];
    
    if ([self.model.state_code isEqualToString:@"4"])// 考试未通过
    {
        mycell.worsdLb.text = @"胜败乃兵家常事，努力争取下次一定过。";
        
        mycell.judgeTeacherBigBtn.hidden = NO;
        mycell.judgeTeacherLittleBtn.hidden = YES;
        mycell.payBtn.hidden = YES;
        mycell.reciveCertificateBtn.hidden = YES;
        [mycell.judgeTeacherBigBtn addTarget:self action:@selector(clickJudgeTeacher:) forControlEvents:UIControlEventTouchUpInside];
    }
    else if ([self.model.state_code isEqualToString:@"5"])// 考试已通过
    {
        mycell.worsdLb.text = @"恭喜你通过考试请再接再厉哦。";
        
        mycell.judgeTeacherLittleBtn.hidden = NO;
        mycell.payBtn.hidden = NO;
        mycell.judgeTeacherBigBtn.hidden = YES;
        mycell.reciveCertificateBtn.hidden = YES;
        
        [mycell.judgeTeacherLittleBtn addTarget:self action:@selector(clickJudgeTeacher:) forControlEvents:UIControlEventTouchUpInside];
        
        [mycell.payBtn addTarget:self action:@selector(payBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        [mycell.reciveCertificateBtn addTarget:self action:@selector(reciveCertificate:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    if ([self.model.major_name isEqualToString:@"音乐基础"])
    {
        mycell.testItemImg.image = [UIImage imageNamed:@"Img_myTestStatus_musicBase"];
    }
    else if ([self.model.major_name isEqualToString:@"爵士鼓"])
    {
        mycell.testItemImg.image = [UIImage imageNamed:@"img_myTestStatus_jueshigu"];
    }
    else if ([self.model.major_name isEqualToString:@"电吉他"])
    {
        mycell.testItemImg.image = [UIImage imageNamed:@"img_myTestStatus_dianjita"];
    }
    else if ([self.model.major_name isEqualToString:@"电贝司"])
    {
        mycell.testItemImg.image = [UIImage imageNamed:@"img_myTestStatus_dianbeisi"];
    }
    
    mycell.testNameLb.text = self.model.major_name;
    
    if ([mycell.testNameLb.text isEqualToString:@"音乐基础"])
    {
        mycell.testNameLb.text = @"音乐理论";
    }
    
    NSString *str = @"地点:  ";
    if (self.model.exam_site_name)
    {
        mycell.addrLb.text = [str stringByAppendingString:self.model.exam_site_name];
    }
    
    mycell.testTimeLb.text = self.model.exam_time;
    
    if (self.model.grade_num)
    {
        if ([mycell.testNameLb.text isEqualToString:@"音乐理论"])
        {
            mycell.testLevelLb.text = [CommFunc getMusicBaseLevel:self.model.grade_num];
        }
        else
        {
            mycell.testLevelLb.text = [self.model.grade_num stringByAppendingString:@"级"];
        }
    }
    mycell.phoneNumLb.text = self.model.tel;
    mycell.detailLb.text = self.model.detail;
    
    if (self.model.state_msg)
    {
        [mycell.testResultBtn setTitle:self.model.state_msg forState:UIControlStateNormal];
    }
}

//评价老师点击事件
-(void)clickJudgeTeacher:(UIButton *)sender
{
    EvaluationTeacherViewController *vc = [EvaluationTeacherViewController create];

    if(self.model == nil)
    {
        return;
    }
    vc.exam_Id = self.model.id;
    vc.teacherId = self.model.monitor_teacher_id;
    vc.monitor_give_score = self.model.monitor_give_score;
    
    [self.navigationController pushViewController:vc animated:YES];	
}

-(void)setShowreciveCertificateBtn
{
    if (self.myCell)
    {
        self.myCell.reciveCertificateBtn.hidden = NO;
        self.myCell.payBtn.hidden = YES;
    }
}

//-(void)payResultOtherProcess:(NSDictionary *)resultDic
//{
//    if ([resultDic[@"resultStatus"] isEqualToString:@"9000"] )
//    {
//        [self.navigationController popViewControllerAnimated:YES];
//    }
//}



@end





























